package com.sanji.pay.yeepay.web;

import com.sanji.pay.pay.entity.PayOrder;
import com.sanji.pay.pay.service.PayOrderService;
import com.sanji.pay.pay.vo.PayResult;
import com.sanji.pay.yeepay.entity.YEEPay;
import com.sanji.pay.yeepay.pojo.YEEPayPojo;
import com.sanji.pay.yeepay.service.YeePayService;
import com.yeepay.Configuration;
import com.yeepay.PaymentForOnlineService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 易宝支付(form表单发起的支付请求)
 * Created by cbh on 2017/9/4.
 */
@Controller
@RequestMapping("/api/yeePay")
public class YeePayController {
  private static final Logger logger = Logger.getLogger(YeePayController.class);

  @Autowired
  private YeePayService yeePayService;
  @Autowired
  private PayOrderService payOrderService;


  /**
   * 易宝回调
   * @param r0_Cmd
   * @param r1_Code
   * @param r2_TrxId
   * @param r3_Amt
   * @param r4_Cur
   * @param r6_Order
   * @param r7_Uid
   * @param r8_MP
   * @param r9_BType
   * @param rp_PayDate
   * @param hmac
   * @param model
   * @return
   */
  @RequestMapping("/toYEEPayRetrun")
  public String yeePayCallback(@RequestParam("r0_Cmd")String r0_Cmd,
                               @RequestParam("r1_Code")String r1_Code,
                               @RequestParam("r2_TrxId")String r2_TrxId,
                               @RequestParam("r3_Amt")String r3_Amt,
                               @RequestParam("r4_Cur")String r4_Cur,
                               @RequestParam("r6_Order")String r6_Order,
                               @RequestParam("r7_Uid")String r7_Uid,
                               @RequestParam("r8_MP")String r8_MP,
                               @RequestParam("r9_BType")String r9_BType,
                               @RequestParam("rp_PayDate")String rp_PayDate,
                               @RequestParam("hmac")String hmac,
                               Model model){
    PayResult payResult = new PayResult();
    try {
      boolean isOK = false;
      // 校验返回数据包
      isOK = PaymentForOnlineService.verifyCallback(hmac,
              Configuration.getInstance().getValue("p1_MerId"), r0_Cmd, r1_Code,
              r2_TrxId, r3_Amt, r4_Cur, "三际手机批发支付",
              r6_Order, r7_Uid, r8_MP, r9_BType,
              Configuration.getInstance().getValue("keyValue"));
      logger.info("查看校验是否返回成功=====================" + isOK);
      if (isOK) {
        // 在接收到支付结果通知后，判断是否进行过业务逻辑处理，不要重复进行业务逻辑处理
        if (r1_Code.equals("1")) {
          // 产品通用接口支付成功返回-浏览器重定向
          if (r9_BType.equals("1")) {
            // System.out.println("callback方式:产品通用接口支付成功返回-浏览器重定向");
            // 产品通用接口支付成功返回-服务器点对点通讯
          } else if (r9_BType.equals("2")) {
            // 如果在发起交易请求时 设置使用应答机制时，必须应答以"success"开头的字符串，大小写不敏感
            // System.out.println("SUCCESS");
            // 产品通用接口支付成功返回-电话支付返回
          }
          // System.out.println("该交易流水号已经处理!");
          YEEPay oldYEEPay = yeePayService.findByPayNum(r6_Order);
          if(oldYEEPay.getResultCode() != "1"){
            YEEPayPojo yeePayPojo = new YEEPayPojo();
            yeePayPojo.setR0_Cmd(r0_Cmd);
            yeePayPojo.setR1_Code(r1_Code);
            yeePayPojo.setR2_TrxId(r2_TrxId);
            yeePayPojo.setR3_Amt(r3_Amt);
            yeePayPojo.setR4_Cur(r4_Cur);
            yeePayPojo.setR5_Pid("三际手机批发支付");
            yeePayPojo.setR6_Order(r6_Order);
            yeePayPojo.setR7_Uid(r7_Uid);
            yeePayPojo.setR8_MP(r8_MP);
            yeePayPojo.setR9_BType(r9_BType);
            yeePayPojo.setRp_PayDate(rp_PayDate);
            yeePayPojo.setHmac(hmac);
            YEEPay yeePay = yeePayService.saveReturnYeePay(yeePayPojo);
            //返回给商家支付成功或失败信息
            yeePayService.callbacktoMerchant(yeePay);

            payResult.setCode("1");
            payResult.setMessage("客官您已付款！我们会尽快安排发货，请耐心等待");
            logger.info("跳转到支付成功页面");
          }else{
            payResult.setCode("1");
            payResult.setMessage("客官您已付款！我们会尽快安排发货，请耐心等待");
          }
        }
      } else {
        logger.info("交易(付款)签名被篡改! 商家支付单号:" + r1_Code);
        payResult.setCode("2");
        payResult.setMessage("支付失败,请您重新进行支付");
        PayOrder payOrder = payOrderService.findByPayNumber(r6_Order);
        payOrder.setStatus(PayOrder.PayStatus.FAILURE);
        payOrder.setDealType("yeePay");
        payOrderService.save(payOrder);
      }
    } catch (Exception e) {
      logger.info("订单支出现异常" + e.getMessage());
    }
    model.addAttribute("result",payResult);
    return "payment/payment_result";
  }
}
